<?php

namespace addons\member\user\controller;

class Member extends \web\user\controller\AddonUserBase{
    
    public function index(){
        $typeM = new \addons\member\model\LevelConfig();
        $level_list = $typeM->getDataList(-1,-1,'','id,title,level','id asc');
        $this->assign('level_list',$level_list);
        return $this->fetch();
    }
    
    public function loadList(){
        $keyword = $this->_get('keyword');
        $is_auth = $this->_get('is_auth');
        $level = $this->_get('level');
        $is_frozen = $this->_get('is_frozen');
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        $filter = ' a.logic_delete=0 ';
        if ($startDate != null && $endDate != null)
            $filter .= ' and (a.register_time >= \'' . $startDate . ' 00:00:00\' and a.register_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (a.register_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (a.register_time <= \'' . $endDate . ' 23:59:59\')';

        if ($keyword != null) {
            // $filter .= ' and (a.username like \'%' . $keyword . '%\')';
            $filter .= ' and (a.username like \'%' . $keyword . '%\' or a.phone  like \'%' . $keyword . '%\' or a.email  like \'%' . $keyword . '%\')';
        }

        if ($is_auth != null) {
            $filter .= ' and a.is_auth = ' . $is_auth;
        }
        if ($level != null) {
            $filter .= ' and a.level = ' . $level;
        }
        if ($is_frozen != null) {
            $filter .= ' and a.is_frozen = ' . $is_frozen;
        }

        $m = new \addons\member\model\MemberAccountModel();
        $total = $m->getMemberTotal($filter);
        $order = 'a.id desc';
        $fileds = 'a.*,b.username as to_user,b.phone as to_phone';
        $rows = $m->getMemberList($this->getPageIndex(), $this->getPageSize(), $filter, $fileds, $order);
        $level_data = (new \addons\member\model\LevelConfig)->column('level,title');
        foreach ($rows as $key => &$v) {
            $v['level_title'] = '普通会员';
            if($v['level'] > 0){
                $v['level_title'] = $level_data[$v['level']];
            }
        }
        return $this->toDataGrid($total, $rows);
    }
    
    public function edit(){
        $m = new \addons\member\model\MemberAccountModel();
        if(IS_POST){
            $data = $_POST;
            $user_data = $m->getDetail($data['id']);
            if($data['id']>0){
                if($user_data['pid']!=$data['pid']){
                    $res2 = (new \addons\config\model\Crontab)->addCrontab($data['id'],0,0,0,'relation');
                }
            }

            if($data['phone'] != ''){
                $user_phone_find = $m->where(['id' => ['<>', $data['id']], 'phone' => $data['phone']])->find();
                if($user_phone_find){
                    return $this->failData('修改的手机号已存在，请变更');
                }
            }
            if($data['email'] != '') {
                $user_email_find = $m->where(['id' => ['<>', $data['id']], 'email' => $data['email']])->find();
                if ($user_email_find) {
                    return $this->failData('修改的邮箱号已存在，请变更');
                }
            }
            $password = $this->_post("now_password");
            if(!empty($password)){
                if (!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/", $password)) {
                    return $this->failData('请输入6~20位字母数字密码');
                }
                $data['password'] = md5($password);
            }
            $pay_password = $this->_post('now_pay_password');
            if(!empty($pay_password)){
                if (!preg_match("/^[0-9]{6}$/", $pay_password)) {
                    return $this->failData('请输入6位数字交易密码');
                }
                $data['pay_password'] = md5($pay_password);
            }

            if($data['level'] != $user_data['level']){
                $data['admin_level'] = $data['level'];
            }

            if($data['id']){
                $m->save($data);
                //添加管理日志
                $this->addLog(self::LOG_EDIT,'修改会员资料',$data, $data['id']);
                return $this->successData();
            }else{
                return $this->failData('用户id为空');
            }
        }else{
            $list = $m->field('id,username,phone')->where('logic_delete=0')->order('id asc')->select();
            $this->assign('user_list', json_encode($list, 256));
            $this->assign('id', $this->_get('id'));
            $this->setLoadDataAction('loadData');
            return $this->fetch();
        }
    }
    
    public function loadData() {
        $id = $this->_get('id');
        $m = new \addons\member\model\MemberAccountModel();
        $data = $m->getDetail($id);
        return $data;
    }
    
    public function select_user(){
        $is_actor = $this->_get('is_actor')>0?1:0;
        $this->assign('is_actor',$is_actor);
        return $this->fetch();
    }

    public function loadSelectUser(){
        $keyword = $this->_get('keyword');
        $is_actor = $this->_get('is_actor');
        $filter = '1=1 ';
        if ($keyword != null) {
            $filter .= ' and (id like \'%' . $keyword . '%\' or username like \'%' . $keyword . '%\' or phone  like \'%' . $keyword . '%\')';
            // $filter .= ' and username like \'%' . $keyword . '%\'';
        }
        if ($is_actor != null) {
            $filter .= ' and is_actor =1';
            // $filter .= ' and username like \'%' . $keyword . '%\'';
        }
        $m = new \addons\member\model\MemberAccountModel();
        $total = $m->getTotal($filter);
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter);
        return $this->toDataGrid($total, $rows);
    }

    /**
     * 认证
     */
    public function auth(){
       if(IS_POST){
           $is_auth = $this->_post('is_auth');
           if($is_auth == ''){
               $is_auth = 1;
           }
           $user_id = $this->_post('id');
           if($is_auth && $user_id){
                $m = new \addons\member\model\MemberAccountModel();
                $data['id'] = $user_id;
                $data['is_auth'] = $is_auth;
                if($is_auth == 1){
                    $data['level'] = 1;
                }

                if($is_auth == -1){
                   $auth_why = $this->_post('auth_why');
                   if($auth_why == ''){
                       return $this->failData('驳回必填原因');
                   }
                   $data['auth_why'] = $auth_why;
                }

                $ret = $m->save($data);

                if($is_auth == 1){
                    $equipOrderM = new \addons\equip\model\EquipOrder();
                    $order_data = $equipOrderM->where(['user_id' => $user_id, 'e_id' => 1])->find();
                    //赠送体验任务包
                    if(empty($order_data)){
                        $equipM = new \addons\equip\model\Equip();
                        $e_id = 1;
                        $equip_data = $equipM->getDetail($e_id);
                        $add_data = [
                            'e_id' => $equip_data['id'],
                            'user_id' => $user_id,
                            'order_sn' => 'Drw'.date('YmdHis').rand(100000,999999),
                            'amount' => $equip_data['min_amount'],
                            'total_amount' => $equip_data['max_amount'],
                            'earnings_tax' => $equip_data['earnings_tax'],
                            'cycle_number' => $equip_data['cycle_number'],
                            'kof_day_tax' => $equip_data['kof_day_tax'],
                            'days_release' => $equip_data['days_release'],
                            'hashrate_amount' => $equip_data['hashrate_amount'],
                            'type' => $equip_data['type'],
                            'limit_num' => $equip_data['limit_num'],
                            'release_balance_type' => $equip_data['release_balance_type'],
                            'create_time' => NOW_DATETIME,
                            'end_time' => date("Y-m-d H:i:s", (time() + ($equip_data['cycle_number'] * 86400))),
                        ];

                        $re_add = $equipOrderM->add($add_data);
                        if(!$re_add){
                            return $this->failData('赠送体验任务包失败，请稍候再试');
                        }
                    }
                }
                if($ret > 0){
                    //添加管理日志
                    $this->addLog(self::LOG_EDIT, 'Member', $data, 0, '用户认证');
                    return $this->successData();
                }
           }else{
               return $this->failData('缺少参数');
           }
       }else{
           $this->assign('id',$this->_get('id'));
           $this->setLoadDataAction('loadCard');
           return $this->fetch();
       }
    }


    /**
     * 直播申请
     */
    public function is_anchor(){
        return $this->fetch();
    }

    /**
     * 用户认证列表
     */
    public function is_auth(){
        return $this->fetch();
    }
    
    /**
     * 认证
     */
    public function anchor(){
       if(IS_POST){
           $is_auth = $this->_post('is_auth');
           $user_id = $this->_post('id');
           if($is_auth && $user_id){
                $m = new \addons\member\model\MemberAccountModel();
                $data['id'] = $user_id;
                $data['is_anchor'] = $is_auth;
               if($is_auth == -1){
                   $auth_why = $this->_post('auth_why');
                   if($auth_why == ''){
                       return $this->failData('驳回必填原因');
                   }
               }
                $ret = $m->save($data);
                if($ret > 0){
                    //添加管理日志
                    $this->addLog(self::LOG_EDIT, 'Member', $data, 0, '用户认证');
                    return $this->successData();
                }
           }else{
               return $this->failData('缺少参数');
           }
       }else{
           $this->assign('id',$this->_get('id'));
           $this->setLoadDataAction('loadCard');
           return $this->fetch();
       }
    }

    /**
     * 认证成功成为主播
     */
    public function beAnchor($user_id){
        $m = new \addons\member\model\MemberAccountModel();
        $user_info = $m->getDetail($user_id, "id,username,phone");
        $s_info = (new \addons\live\utils\LiveStream())->getStreamInfo();
        $info['user_id'] = $user_info['id'];
        $info['username'] = $user_info['username'];
        $info['phone'] = $user_info['phone'];
        $info['push_url'] = $s_info['ToUrl'].$user_info['phone'];
        $info['pull_url'] = $s_info['FromUrl'].$user_info['phone'];
        $info['status'] = 0;
        $info['create_at'] = NOW_DATETIME;
        $info['update_at'] = NOW_DATETIME;
        $livemodel = new \addons\live\model\LiveShowModel();
        $res = $livemodel->field('id')->where(['phone'=>$info['phone']])->find();
        if($res) return true;
        $res = $livemodel->addLiveStream($info);
        if(!$res) return false;;
        return true;
    }

    /**
     * 加载认证数据
     * @return type
     */
    public function loadCard(){
        $id = $this->_get('id');
        $m = new \addons\member\model\MemberAccountModel();
        $data = $m->getAuthData($id);
        return $data;
    }

    public function add_user() {
        if (IS_POST) {
            //去除信息中的空格
//            $username = trim($this->_post('username',true));
//            if($username == '') return $this->failData('请输入用户名');

            $reg_type = $this->_post('reg_type');
            if($reg_type == 1){
                $phone = trim($this->_post('phone',true));
                if($phone == '') return $this->failData('请输入手机号');

                $data['phone'] = $phone;
            }else{
                $phone = trim($this->_post('email',true));
                if($phone == '') return $this->failData('请输入邮箱号');
                $data['email'] = $phone;
            }
            $pid = $this->_post('pid');
            if($pid < 1) return $this->failData('请输入推荐人');
            $password = $this->_post('password');
            if($password == '') return $this->failData('请输入登陆密码');
            $pay_password = $this->_post('pay_password');
            if($pay_password == '') return $this->failData('请输入交易密码');

            $m = new \addons\member\model\MemberAccountModel();
//            $count = $m->hasRegsterUsername($username);
            if($reg_type == 1){
                $count = $m->hasRegsterPhone($phone);
                if ($count > 0)  return $this->failData('此用户手机号已被注册');
            }else{
                $count = $m->hasRegsterEmail($phone);
                if ($count > 0)  return $this->failData('此用户手机号已被注册');
            }

            $pid_path = $m->getDetail($pid, 'pid_path')['pid_path'];

            if(!empty($pid_path)){
                $pid_path = $pid_path.$pid.',';
            }else{
                $pid_path = ','.$pid.',';
            }
            $data['username'] = $phone;
            $data['pid'] = $pid;
            $data['pid_path'] = $pid_path;
            $data['register_time'] = NOW_DATETIME;
            $data['password'] = md5($password);
            $data['pay_password'] = md5($pay_password);
            $data['invite_code'] = createRandCode(6);
//            $data['head_img'] = '/uploads/slider/20201112/head.png';

            try {
                $m->startTrans();
                $user_id = $m->add($data);
                if ($user_id > 0) {
//                    $phyM = new \addons\member\model\PhysicalContribution();
//                    $phyM->createPhy($user_id);
//                    $res = $phyM->addPhy($pid_path,1,1);
//                    if (!$res) {
//                        $m->rollback();
//                        return $this->failData("生成业绩记录失败");
//                    }
                    $balanceM = new \addons\member\model\Balance();
                    $bcm = new \addons\config\model\BalanceConf();
                    $type_list = $bcm->getDatas();
                    $flag = true;
                    foreach ($type_list as $k => $type) {
                        $balance = array(
                            'user_id' => $user_id,
                            'type' => $type['type'],
                            'update_time' => NOW_DATETIME,
                        );
                        $res = $balanceM->add($balance);
                        if (!$res) {
                            $flag = false;
                        }
                    }
                    if (!$flag) {
                        $m->rollback();
                        return $this->failData("插入积分出错");
                    }
                    $this->addLog(self::LOG_DEL, '添加会员', $data, $user_id);
                    $m->commit();
                    return $this->successData();
                }
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failData($ex->getMessage());
            }
        } else {
            $list = (new \addons\member\model\MemberAccountModel())->field('id,username')->where(['logic_delete' => 0, 'id' => ['<>', $this->_get('id')]])->order('id asc')->select();
            $this->assign('user_list', json_encode($list, 256));
            $this->assign('id', '');
            return $this->fetch();
        }
    }


    public function add_ticket() {
        if (IS_POST) {
            try {
                $level = $this->_post('level');
                if($level<=0){
                    return $this->failData(lang('请选择正确的等级'));   
                }
                $amount = $this->_post('amount');
                $res = (new \addons\config\model\Crontab)->addCrontab(0,$amount,$amount,$level,'addTicket');
                if(!$res){
                    return $this->failData(lang('奖励发放失败'));   
                }
                return $this->successData();
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failData($ex->getMessage());
            }
        } else {
            $typeM = new \addons\member\model\LevelConfig();
            $level_list = $typeM->getDataList(-1,-1,'level>0','id,title,level','id asc');
            $this->assign('level_list',$level_list);
            $this->assign('id', '');
            return $this->fetch();
        }
    }
    

    private function getRandomString($len, $chars=null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    /**
     * 拨币
     * @return type
     */
    public function add_coin_stock() {
        if (IS_POST) {
            $user_id = $this->_post('id');
            $amount = $this->_post('amount');
            $type = $this->_post('type');
            $remark = $this->_post('remark') ? $this->_post('remark') : '外网转账';
            $memberM = new \addons\member\model\MemberAccountModel();
            $m = new \addons\member\model\Balance();
            $m->startTrans();
            $balance = $m->getBalanceByType($user_id, $type);
            try {
                if (!empty($balance)) {
                    $id = $balance['id'];
                    $before_amount = $balance['amount'];
                    $balance['type'] = $type;
                    $balance['amount'] = $before_amount + $amount;
                    $balance['update_time'] = NOW_DATETIME;
                    $balance['last_bone_time'] = NOW_DATETIME;
                    $m->save($balance);
                } else {
                    $before_amount = 0;
                    $balance['user_id'] = $user_id;
                    $balance['type'] = $type;
                    $balance['amount'] = $amount;
                    $balance['update_time'] = NOW_DATETIME;
                    $balance['last_bone_time'] = NOW_DATETIME;
                    $id = $m->add($balance);
                }
                if ($id > 0) {
                    $rm = new \addons\member\model\TradingRecord();
                    $after_amount = $balance['amount'];
                    $asset_type = $type;
                    if ($amount > 0) {
                        $change_type = 1; //增加
                    } else {
                        $change_type = 0; //减少
                        $amount = abs($amount);
                    }
                    $type = 3; //后台拨币
//                    $remark = '系统后台拨币';
                    $r_id = $rm->addRecord($user_id, $amount, $before_amount, $after_amount, $asset_type, $type, $change_type, 0, $remark);
                    if ($r_id > 0) {
                        $m->commit();
                        //添加管理日志
                        $this->addLog(self::LOG_EDIT, '拨币', $_POST, $user_id);
                        return $this->successData();
                    }
                } else {
                    $m->rollback();
                    return $this->failData('拨币失败');
                }
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failData($ex->getMessage());
            }
        } else {
            $m = new \addons\config\model\BalanceConf();
            $list = $m->getDataList(-1, -1, ' 1=1 ', 'id,name', 'order_index asc');
            $this->assign('types', $list);
            $this->assign('id', $this->_get('id'));
            return $this->fetch();
        }
    }

    public  function getTree($pid='0')
    {
        $memberM = new \addons\member\model\MemberAccountModel();
        $balanceM = new \addons\member\model\Balance();
        $where=array("pid"=>$pid);
        $list = $memberM->where($where)->order('id asc')->select();
        if(is_array($list)){
            $html = '';
            foreach($list as $k => $v)
            {
                $map['pid']=$v['id'];
                $count=$memberM->where($map)->count(1);
                $balance_usdt = $balanceM->getBalanceAmountByType($v['id'],1);
                $balance_bean = $balanceM->getBalanceAmountByType($v['id'],2);
                $class=$count==0 ? 'fa-user':'fa-sitemap';

                if($v['pid'] == $pid)
                {
                    //父级找到子级
                    $html .= '<li style="display:none" >';
                    $html .= '<span><i class="icon-plus-sign '.$class.' blue "></i>';
                    $html .= $v['username'];
                    $html .= '</span>';

                    $html .= $this->getTree($v['id']);
                    $html = $html."</li>";
                }
            }
            return $html ? '<ul>'.$html.'</ul>' : $html ;
        }
    }
    
    public function view_childs(){
        $id = $this->_get('id');
        $m = new \addons\member\model\MemberAccountModel();
        $data = $m->field('id,username,phone,real_name')->where(['id' => $id])->find();
        if($data){
            if($data['real_name'] == null){
                $data['real_name'] = '未认证';
            }
            $data['children'] = $m->getChildssByPID($id);
        }
        $this->assign('data', json_encode($data, 256));
        $this->assign('user_id',$id);
        return $this->fetch();
    }
//
//    public function view_childs(){
//        $id = $this->_get('id');
//        $m = new \addons\member\model\MemberAccountModel();
//        $data = $m->alias('m')->join('member_physical_contribution c','c.user_id=m.id')->where('m.id',$id)->field('m.id,pid,username,push_total,team_strength,activity,single_activity')->find();
//        if($data){
//            $data['team_strength'] += 0;
//            $data['activity'] += 0;
//            $data['single_activity'] += 0;
//            $data['children'] = $m->getChildssByPID($id);
//        }
//        $this->assign('data', json_encode($data, 256));
//        $this->assign('user_id',$id);
//        return $this->fetch();
//    }

    public function load_childs(){
        $pid = $this->_get('pid');
        $m = new \addons\member\model\MemberAccountModel();
        return $m->getChildssByPID($pid);
    }
    

    
    // public function load_childs(){
    //     $aid = $this->_get('aid');
    //     $m = new \addons\member\model\MemberAccountModel();
    //     return $m->getChildsByAID($aid);
    // }


    public function view_balance(){
        $id = $this->_get('id');
        $m = new \addons\member\model\Balance();
        $filter = 'user_id='.$id;
        $list = $m->getList(-1,-1,$filter);
        $this->assign('data',$list);
        return $this->fetch();
    }
    
    
    
    public function change_frozen(){
        $id = $this->_post('id');
        $status = $this->_post('status');
        if($status != 0){
            $status = 1;
        }
        $m = new \addons\member\model\MemberAccountModel();
        try{
            $ret = $m->changeFrozenStatus($id, $status);
            if($ret > 0){
                return $this->successData();
            }else{
                $message = '操作失败';
                return $this->failData($message);
            }
        } catch (\Exception $ex) {
            return $this->failData($ex->getMessage());
        }
    }
  

    /**
     * 逻辑删除
     * @return type
     */
    public function del(){
        $id = $this->_post('id');
        $m = new \addons\member\model\MemberAccountModel();
        try{
            $where1['id'] = $id;
            $user = $m->where($where1)->find();
            if(!$user){
                return $this->failData('不存在用户');
            }
//            删除账号后退款到推荐人用户 ， 删除的账号下面如果有节点 就不能删除
            $m->startTrans();
            //删除资产
            $b = new \addons\member\model\Balance();
            $where['user_id'] = $id;
            $del = $b->where($where)->delete();
            $ret = $m->deleteData($id);
            if($ret > 0){
                $m->commit();
                //添加管理日志
                $this->addLog(self::LOG_DEL,'删除会员',$user, $id);
                return $this->successData();
            }else{
                $m->rollback();
                $message = '删除失败';
                return $this->failData($message);
            }
        } catch (\Exception $ex) {
            $m->rollback();
            return $this->failData($ex->getMessage());
        }
    }
  
    
    
    public function export(){
        set_time_limit(0);
        ob_end_clean();
        $keyword = $this->_get('keyword');
        $filter = 'logic_delete=0';
        if ($keyword != null) {
            $filter .= ' and username like \'%' . $keyword . '%\'';
        }
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        if ($startDate != null && $endDate != null)
            $filter .= ' and (register_time >= \'' . $startDate . ' 00:00:00\' and register_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (register_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (register_time <= \'' . $endDate . ' 23:59:59\')';
        
        $fileName = '会员列表_'.NOW_DATETIME.'.csv';
        header('Content-type: text/html;charset=utf-8');
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');
        $header = [
            ['title' => '编号', 'field' => 'id'],
            ['title' => '用户名', 'field'=> 'username'],
            ['title' => '余额', 'field'=> 'balance']

        ];
        // 将数据通过fputcsv写到文件句柄
        // CSV的Excel支持GBK编码，一定要转换，否则乱码
        $head = [];
        foreach($header as $val){
            $head[] = iconv('utf-8', 'gbk', $val['title']);
        }
        fputcsv($fp, $head);
        $m = new \addons\member\model\MemberAccountModel();
        $rows = $m->getExportList($this->getPageIndex(), $this->getPageSize(), $filter);
        $i = 0;
        // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;
        $data = [];
        foreach ($rows as &$row) {
            if ($limit == $i) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $i = 0;
            }
            $arr = [];
            foreach ($header as $key => $val) {
                $value = isset($row[$val['field']]) ? $row[$val['field']] : "";
                $arr[$val['field']] = iconv('utf-8', 'gbk//IGNORE', $value."\t");
            }
            fputcsv($fp, $arr);
        }
    }

    /**
     * 修改等级
     */
    public function level_update(){
        $m = new \addons\config\model\LevelConfig();
        $accountM = new \addons\member\model\MemberAccountModel();
        $balanceM = new \addons\member\model\Balance();
        $TradingRecordM = new \addons\member\model\TradingRecord();
        $id = $this->_get('id');
        if(IS_POST){
            try{
                $amount_type = 1;
                $level_id = $this->_post('level_id');
                $level_amount = $m->getDetail($level_id, 'amount');
                $re = $balanceM->where(['user_id' => $id, 'type' => 1, 'amount' => ['>=', $level_amount['amount']]])->find();
                if(empty($re)){
                    return $this->failData('金额不足，无法升级');
                }
                $balanceM->startTrans();
                $re_balance = $balanceM->updateBalance($id, $amount_type, $level_amount['amount'], false);
                if(!$re_balance){
                    $balanceM->rollback();
                    return $this->failData('扣款失败，升级失败');
                }
                $remark = '管理员升级';
                $re_record = $TradingRecordM->addRecord($id, $level_amount['amount'], $re_balance['before_amount'], $re_balance['amount'], $amount_type, 3, 0, 0, $remark);
                if(!$re_record){
                    $balanceM->rollback();
                    return $this->failData('扣款流水失败，升级失败');
                }
                $re_update = $accountM->where(['id' => $id])->update(['level' => $level_id]);
                if(!$re_update) {
                    $balanceM->rollback();
                    return $this->failData('变更等级失败，升级失败');
                }
                $balanceM->commit();
                $this->topUpReward($id,$level_amount['amount']);
                return $this->successData();
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failData($ex->getMessage());
            }
        }else{
            $accountM = new \addons\member\model\MemberAccountModel();
            $user_level = $accountM->getDetail($id,'level');
            $level_list = $m->where(['id' => ['>', $user_level['level']]])->where(['id' => ['>', 2]])->select();
            $this->assign('level_list', $level_list);
            $this->assign('id', $id);
            return $this->fetch();
        }
    }

    /**
     * 取消代理
     */
    public function cancle_area(){
        $id = $this->_post('id');
        $m = new \addons\member\model\MemberAccountModel();
        try{
            $res = $m->where('id',$id)->update(['is_agent'=>0,'region_id'=>0]);
            if($res){
                return $this->successData();
            }else{
                $message = '删除失败';
                return $this->failData($message);
            }
        } catch (\Exception $ex) {
            return $this->failData($ex->getMessage());
        }
    }

    /**
     * 设置代理
     */
    public function set_area(){
        $accountM = new \addons\member\model\MemberAccountModel();
        $id = $this->_get('id');
        if(IS_POST){
            try{
                $type = $this->_post('agent_type');
                $area = $this->_post('area');
                $province = $this->_post('province');
                $city = $this->_post('city');
                if(!in_array($type, [0,1,2,3,4])){
                    return $this->failData('代理类型错误');
                }
                if($type==0){
                    $res = $accountM->where('id',$id)->update(['is_agent'=>0,'region_id'=>0]);
                }else{
                    if($type==1){
                        $area = $area;
                    }elseif($type==2){
                        $area = $city;
                    }else{
                        $area = $province;
                    }
                    $ex = $accountM->where('region_id',$area)->value('id');
                    if($ex) return $this->failData('当前区域已有代理');
                    $res = $accountM->where('id',$id)->update(['is_agent'=>$type,'region_id'=>$area]);
                }
                if(!$res){
                    return $this->failData('设置代理失败');
                }
                return $this->successData();
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failData($ex->getMessage());
            }
        }else{
            $user_data = $accountM->field('is_agent,region_id')->where('id',$id)->find();
            $city = [];
            $area = [];
            $areaM = new \addons\config\model\Area;
            $province = $areaM->where('pid',0)->select();
            if($user_data['is_agent']>0){
                $area_info = $areaM->where('id',$user_data['region_id'])->find();
                if($user_data['is_agent']==1){
                    $area = $areaM->where('pid',$area_info['pid'])->select();
                    $city_id = $areaM->where('id',$user_data['region_id'])->value('pid');
                    $province_id = $areaM->where('id',$city_id)->value('pid');
                    $city = $areaM->where('pid',$province_id)->select();
                }elseif($user_data['is_agent']==2){
                    $city = $areaM->where('pid',$area_info['pid'])->select();
                    $area = $areaM->where('pid',$user_data['region_id'])->select();
                }
            }else{
                $city = $areaM->where('pid',$province[0]['id'])->select();
                $area = $areaM->where('pid',$city[0]['id'])->select();   
            }
            $this->setLoadDataAction('loadAreaData');
            $this->assign('id', $id);
            $this->assign('province', $province);
            $this->assign('city', $city);
            $this->assign('area', $area);
            return $this->fetch();
        }
    }


    public function loadAreaData() {
        $accountM = new \addons\member\model\MemberAccountModel();
        $id = $this->_get('id');
        $user_data = $accountM->field('is_agent,region_id,level')->where('id',$id)->find();
        if($user_data['is_agent']>0){
            $areaM = new \addons\config\model\Area;
            if($user_data['is_agent']==1){
                $area = $user_data['region_id'];
                $city = $areaM->where('id',$user_data['region_id'])->value('pid');
                $province = $areaM->where('id',$city)->value('pid');
            }elseif($user_data['is_agent']==2){
                $province = $areaM->where('id',$user_data['region_id'])->value('pid');
                $city = $user_data['region_id'];
                $area = 0;
            }else{
                $province = $user_data['region_id'];
                $area = 0;
                $city = 0;
            }
            $data['agent_type'] = $user_data['is_agent'];
        }else{
            $agent_type = 0;
            // if($user_data['level']==5){
            //     $agent_type = 1;
            // }elseif($user_data['level']==6){
            //     $agent_type = 2;
            // }elseif($user_data['level']==7){
            //     $agent_type = 3;
            // }
            $data['agent_type'] = $agent_type;
            $province = 0;
            $area = 0;
            $city = 0;
        }
        $data['agent_type'] = $data['agent_type'];
        $data['province'] = $province;
        $data['area'] = $area;
        $data['city'] = $city;
        return $data;
    }

    public function getArea(){
        $areaM = new \addons\config\model\Area;
        $pid = $this->_post('pid');
        if($pid>0){
            $city = $areaM->where('pid',$pid)->select();
            return $city;
        }
    }


    /**
     * 冻结账号
     * @return array|mixed|string
     */
    public function freeze(){
        $id = $this->_post('id');
        if (IS_POST) {
            $accountM = new \addons\member\model\MemberAccountModel();
            $user_is_frozen = $accountM->getDetail($id,'is_frozen')['is_frozen'];
            try {
                $frozen_reasons = $this->_post('frozen_reasons');
                if($frozen_reasons == '')$this->failData('请输入冻结原因');
                if($user_is_frozen == 1) return $this->failData('当前用户已冻结');

                $res = $accountM->where(['id' => $id])->update(['is_frozen' => 1, 'frozen_reasons' => $frozen_reasons]);
                if(!$res){
                    return $this->failData('冻结失败');
                }
                //添加管理日志
                $this->addLog(self::LOG_EDIT, 'Member', [], $id, '冻结用户');
                return $this->successData();

            } catch (\Exception $e) {
                return $this->failData($e->getMessage());
            }
        } else {
            $id = $this->_get('id');
            $this->assign('id', $id);
            return $this->fetch();
        }
    }

    /**
     * 设置用户是否需要手续费
     * @return array|mixed|string
     */
    public function poundage(){

        $id = $this->_post('id');
        $type = $this->_post('type');
        $accountM = new \addons\member\model\MemberAccountModel();
        try {
            $user_is_poundage = $accountM->getDetail($id,'is_poundage')['is_poundage'];
            if($type == 0){
                if($user_is_poundage == 1) return $this->failData('当前已是不需要手续费，请勿重复提交');
                $res = $accountM->where(['id' => $id])->update(['is_poundage' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            }else{
                if($user_is_poundage == 0) return $this->failData('当前已是需要手续费，请勿重复提交');
                $res = $accountM->where(['id' => $id])->update(['is_poundage' => 0, 'update_time' => date('Y-m-d H:i:s')]);
            }
            if(!$res){
                return $this->failData('设置失败');
            }
            //添加管理日志
            $this->addLog(self::LOG_EDIT, 'Member', [], $id, '设置用户是否需要手续费');
            return $this->successData();

        } catch (\Exception $e) {
            return $this->failData($e->getMessage());
        }

    }

    /**
     *解冻账号
     * @return array|mixed|string
     */
    public function thaw(){
        $id = $this->_post('id');
        $accountM = new \addons\member\model\MemberAccountModel();
        $user_is_frozen = $accountM->getDetail($id,'is_frozen')['is_frozen'];
        try {
            if($user_is_frozen == 0) return $this->failData('当前用户已解冻');
            $res = $accountM->where(['id' => $id])->update(['is_frozen' => 0, 'frozen_reasons' => '']);
            if(!$res){
                return $this->failData('解冻失败');
            }
            //添加管理日志
            $this->addLog(self::LOG_EDIT, 'Member', [], $id, '解冻用户');
            return $this->successData();

        } catch (\Exception $e) {
            return $this->failData($e->getMessage());
        }
    }

    public function user_address(){
        return $this->fetch();
    }

    public function loadUserAddressList(){
        $keyword = $this->_get('keyword');
        $filter = 'logic_delete=0';
        if ($keyword != null) {
            $filter .= ' and (username like \'%' . $keyword . '%\')';
        }
        $m = new \addons\shop\model\MemberAddress();
        $total = $m->getAddressTotal($filter);
        $rows = $m->getAddressList($this->getPageIndex(), $this->getPageSize(), $filter);
        return $this->toDataGrid($total, $rows);
    }

    /**
     * 未审核认证的用户
     * @return mixed|string
     */
    public function select_auth_user(){
        return $this->fetch();
    }
    public function loadSelectAuthUser(){
        $keyword = $this->_get('keyword');
        $filter = ' is_auth = 0 ';
        if ($keyword != null) {
            $filter .= ' and phone like \'%' . $keyword . '%\'';
        }
        $m = new \addons\member\model\MemberAccountModel();
        $total = $m->getTotal($filter);
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter, 'id,username,phone', 'id asc');
        return $this->toDataGrid($total, $rows);
    }

    /**
     * 认证身份证详情
     * @return mixed|string
     */
    public function auth_view(){
        $id = $this->_get('id');
        $accountM = new \addons\member\model\MemberAccountModel();
        $data = $accountM->getDetail($id,'id_face,id_back,real_name,card_no');
        $this->assign('data', $data);
        $this->assign('id', $id);
        return $this->fetch();
    }


    /**
     * 查看实名
     */
    public function look(){
        $id = $this->_get('id');
        $accountM = new \addons\member\model\MemberAccountModel;
        $push_count = $accountM->where('pid',$id)->count();
        $push_total = $accountM->where(['pid_path'=>['like',',%'.$id.'%,']])->count();
        $puah_auth_total = $accountM->where(['pid_path'=>['like',',%'.$id.'%,'],'is_auth'=>1])->count();
        $data['push_count'] = $push_count;
        $data['auth_num'] = $puah_auth_total;
        $data['unauth_num'] = $push_total-$puah_auth_total;
        $this->assign('id', $id);
        $this->assign('data', $data);
        return $this->fetch();
    }

}


